/*
 * Copyright (c) 2016. For Intelligent Group.
 */

package com.intelligent.mts.da.handler;


import com.intelligent.mts.core.utils.AppConst;
import com.intelligent.mts.da.message.ReceiveServerMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Julia.Zhou on 2016/07/20.
 */
public class HeartbeatClientHandler extends ChannelInboundHandlerAdapter {

	public static Logger logger = LoggerFactory.getLogger(HeartbeatHandler.class);

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		logger.info("reading----" + msg);
		ReceiveServerMessage receiveMessage = (ReceiveServerMessage) msg;
		String	returnMessage = AppConst.START_HEARTBEAT + AppConst.SEPARATOR + "abc;123;" + AppConst.RESULT_OK + AppConst.END_FLAG;
		ctx.writeAndFlush(returnMessage);
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		super.channelReadComplete(ctx);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		logger.warn("Unexpected exception from com.intelligent.mts.da.handler " + cause);
		ctx.fireExceptionCaught(cause);
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
		if (!(evt instanceof IdleStateEvent)) {
			return;
		}

		IdleStateEvent e = (IdleStateEvent) evt;
		if (e.state() == IdleState.ALL_IDLE) {
			// The connection was OK but there was no traffic for last period.
			logger.error("Disconnecting due to no inbound traffic");
			ctx.close();
		}
	}

}
